package nl.maarten.docenthelp.entity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;

public class Session 
{
	private String ID;
	
	private Socket socket;
	
	private DatagramSocket udpSocket;
	
	private BufferedWriter out;
	
	private BufferedReader in;
	
	private DatagramPacket packet;
	
	private int udpServerPort;
	
	public Session(String ID, Socket socket, int udpServerPort)
	{
		this.ID = ID;
		this.socket = socket;
		this.udpServerPort = udpServerPort;
		
		try
		{
			this.udpSocket = new DatagramSocket();
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
		
		init();
	}
	
	private void init()
	{
		try 
		{
			out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			sendMessage( "Hello server!" );
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	public DatagramSocket getUdpSocket()
	{
		return udpSocket;
	}
	
	public void sendMessage( String message )
	{
		packet = new DatagramPacket( message.getBytes(), message.getBytes().length, socket.getInetAddress(), udpServerPort);
		try
		{
			udpSocket.send(packet);
		}
		catch( IOException e )
		{
			e.printStackTrace();
		}
	}
	
	public String getIPAddress()
	{
		return socket.getInetAddress().toString();
	}

	public String getID() 
	{
		return ID;
	}
	
	public void setID(String ID)
	{
		this.ID = ID;
	}
	public Socket getSocket()
	{
		return socket;
	}

	public BufferedWriter getOut() 
	{
		return out;
	}

	public BufferedReader getIn() 
	{
		return in;
	}
}
